frontend {{ item.haproxy_service_name }}-front
{% if item.haproxy_balance_type == "http" %}
{% set mode = "http" %}
{% else %}
{% set mode = "tcp" %}
{% endif %}
{% for bind_host in item.haproxy_bind_hosts | unique %}
    bind {{ bind_host }}:{{ item.haproxy_port }}
{% endfor %}

{% if item.haproxy_balance_type == "http" %}
    option httplog
    option forwardfor except 127.0.0.0/8
    option http-server-close

    {%- set request_option = "http" %}
{% else %}
    option  tcplog
    {%- set request_option = "tcp" %}
{% endif %}
{% for option in item.haproxy_frontend_options|default([]) %}
    option {{ option }}
{% endfor %}

{% if item.haproxy_timeout_client is defined %}
    timeout client {{ item.haproxy_timeout_client }}
{% endif %}

    mode {{ mode }}
    default_backend {{ item.haproxy_service_name }}-back

{% if item.haproxy_backend_port is not defined %}
  {% set haproxy_backend_port = item.haproxy_port %}
{% else %}
  {% set haproxy_backend_port = item.haproxy_backend_port %}
{% endif %}

{% if item.haproxy_check_port is not defined %}
  {% set haproxy_check_port = haproxy_backend_port %}
{% else %}
  {% set haproxy_check_port = item.haproxy_check_port %}
{% endif %}

backend {{ item.haproxy_service_name }}-back
    mode {{ mode }}
    balance {{ item.haproxy_balance_alg|default("leastconn") }}
{% for option in item.haproxy_backend_options|default([]) %}
    option {{ option }}
{% endfor %}
{% for opt in item.haproxy_backend_extras | default([]) %}
    {{ opt }}
{% endfor %}
{% if item.haproxy_timeout_server is defined %}
    timeout server {{ item.haproxy_timeout_server }}
{% endif %}
{% set check_option = "" %}
{% if item.haproxy_balance_type == "https" %}
{% set check_option = "check-ssl"  %}
{% endif %}
{% set hosts_count = item.haproxy_backend_nodes|count + item.haproxy_backup_nodes|default([])|count %}
{% for host_name in item.haproxy_backend_nodes %}
    server {{ host_name }} {{ hostvars[host_name]['ip']['mgmt'] }}:{{ haproxy_backend_port }} check {{ check_option }} port {{ haproxy_check_port }} inter {{ haproxy_interval }} rise {{ hosts_count }} fall {{ hosts_count }}
{% endfor %}
{% for host_name in item.haproxy_backup_nodes|default([]) %}
    server {{ host_name }} {{ hostvars[host_name]['ip']['mgmt'] }}:{{ haproxy_backend_port }} check {{ check_option }} port {{ haproxy_check_port }} inter {{ haproxy_interval }} rise {{ hosts_count }} fall {{ hosts_count }} backup
{% endfor %}
